<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <title>备件管理系统 - 供应商管理</title>
  <link rel="stylesheet" href="https://unpkg.com/element-plus/dist/index.css">
  <style>
    .el-table__header th {
      background-color: #e1dddd !important;
    }
    #app {
      padding: 20px;
    }
    #loading {
      text-align: center;
      font-size: 18px;
      color: red;
    }
  </style>
</head>
<body>
<div id="app">
  <div id="loading" v-if="loading">正在加载数据，请稍候...</div>
  <div v-else>
    <header class="header">
      <h2 style="margin: 0;">供应商管理</h2>
    </header>

    <main>
      <!-- 退出按钮 -->
      <div style="text-align: right;">
        <el-button type="info" size="small" @click="logout">退出</el-button>
      </div>

      <!-- 新增按钮 + 搜索框 -->
      <div style="margin-bottom: 10px; display: flex; justify-content: space-between;">
        <el-button type="primary" size="medium" @click="showAddDialog = true">新增供应商</el-button>
        <el-input v-model="searchQuery" placeholder="请输入供应商编号或名称" style="width: 200px;"></el-input>
      </div>

      <!-- 表格 -->
      <el-table :data="paginatedSuppliers" border style="width: 100%">
        <el-table-column prop="index" label="序号"></el-table-column>
        <el-table-column prop="name" label="名称"></el-table-column>
        <el-table-column prop="contactPeople" label="联系人"></el-table-column>
        <el-table-column prop="contactPhone" label="联系方式"></el-table-column>
        <el-table-column prop="deliveryTimeliness" label="交货及时率"></el-table-column>
        <el-table-column prop="qualityScore" label="质量评分"></el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="mini" type="danger" @click="deleteSupplier(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
              layout="prev, pager, next"
              :total="computedSuppliers.length"
              v-model:current-page="currentPage"
              :page-size="pageSize"
              style="margin-top: 20px; justify-content: center;">
      </el-pagination>

      <!-- 新增供应商弹窗 -->
      <el-dialog v-model="showAddDialog" title="新增供应商" width="30%">
        <el-form :model="newSupplier" label-position="left" label-width="100px">
          <el-form-item label="名称">
            <el-input v-model="newSupplier.name"></el-input>
          </el-form-item>
          <el-form-item label="联系人">
            <el-input v-model="newSupplier.contactPeople"></el-input>
          </el-form-item>
          <el-form-item label="联系方式">
            <el-input v-model="newSupplier.contactPhone"></el-input>
          </el-form-item>
          <el-form-item label="交货及时率">
            <el-input v-model.number="newSupplier.deliveryTimeliness" type="number"></el-input>
          </el-form-item>
          <el-form-item label="质量评分">
            <el-input v-model.number="newSupplier.qualityScore" type="number"></el-input>
          </el-form-item>
          <div style="text-align: right;">
            <el-button @click="cancelAdd">取消</el-button>
            <el-button type="primary" @click="addSupplier">添加</el-button>
          </div>
        </el-form>
      </el-dialog>
    </main>

    <footer class="footer">
      &copy; 2025 备件管理系统 - 版权所有
    </footer>
  </div>
</div>

<!-- 引入 Vue + Axios + Element Plus -->
<script src="https://unpkg.com/vue@3.2.36/dist/vue.global.prod.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://unpkg.com/element-plus"></script>

<script>
  const { createApp } = Vue;

  const apiClient = axios.create({
    //本机地址
    //baseURL: 'http://localhost:8086',
    //服务器 地址
    baseURL: 'http://8.137.85.243:8086',
    timeout: 5000
  });

  const app = createApp({
    data() {
      return {
        suppliers: [],
        enrichedSuppliers: [],
        newSupplier: {
          name: '',
          contactPeople: '',
          contactPhone: '',
          deliveryTimeliness: null,
          qualityScore: null
        },
        searchQuery: '',
        showAddDialog: false,
        currentPage: 1,
        pageSize: 10,
        loading: true
      };
    },
    computed: {
      computedSuppliers() {
        return this.enrichedSuppliers
                .filter(supplier =>
                        supplier.name.toLowerCase().includes(this.searchQuery.toLowerCase()) ||
                        supplier.id.toString().includes(this.searchQuery.toLowerCase())
                )
                .map((supplier, index) => ({
                  index: index + 1,
                  id: supplier.id,
                  name: supplier.name,
                  contactPeople: supplier.contactPeople || supplier.contact_people || '暂无信息',
                  contactPhone: supplier.contactPhone || supplier.contact_phone || '暂无信息',
                  deliveryTimeliness: supplier.deliveryTimeliness ? supplier.deliveryTimeliness.toFixed(2) : '暂无信息',
                  qualityScore: supplier.qualityScore ? supplier.qualityScore.toFixed(2) : '暂无信息'
                }));
      },
      paginatedSuppliers() {
        const start = (this.currentPage - 1) * this.pageSize;
        const end = start + this.pageSize;
        return this.computedSuppliers.slice(start, end);
      }
    },
    mounted() {
      this.loadSuppliers().finally(() => {
        this.loading = false;
      });
    },
    methods: {
      async loadSuppliers() {
        try {
          const res = await apiClient.get('/api/suppliers/listall');
          const suppliers = res.data;

          this.enrichedSuppliers = await Promise.all(suppliers.map(async (sp) => {
            try {
              const evalRes = await apiClient.get(`/api/supplierevaluations/findbysupplierid/${sp.supplierid}`);
              const evalData = evalRes.data[0] || {};
              return {
                id: sp.supplierid,
                name: sp.name,
                contactPeople: sp.contactPeople || sp.contact_people,
                contactPhone: sp.contactPhone || sp.contact_phone,
                deliveryTimeliness: evalData.deliveryTimeliness,
                qualityScore: evalData.qualityScore
              };
            } catch (err) {
              console.error(`加载供应商 ${sp.supplierid} 评分失败`, err);
              return {
                id: sp.supplierid,
                name: sp.name,
                contactPeople: sp.contactPeople || sp.contact_people,
                contactPhone: sp.contactPhone || sp.contact_phone,
                deliveryTimeliness: null,
                qualityScore: null
              };
            }
          }));
        } catch (err) {
          alert('加载供应商失败: ' + err.message);
        }
      },

      async addSupplier() {
        if (!this.newSupplier.name || !this.newSupplier.contactPeople || !this.newSupplier.contactPhone) {
          alert('请填写完整信息（名称、联系人、联系方式）');
          return;
        }

        const deliveryTimeliness = parseFloat(this.newSupplier.deliveryTimeliness);
        const qualityScore = parseFloat(this.newSupplier.qualityScore);

        if (isNaN(deliveryTimeliness) || isNaN(qualityScore)) {
          alert('交货及时率和质量评分必须为数字');
          return;
        }

        try {
          const supplierRes = await apiClient.post('/api/suppliers/insert', {
            name: this.newSupplier.name,
            contactPeople: this.newSupplier.contactPeople,
            contactPhone: this.newSupplier.contactPhone
          });

          const supplierid = supplierRes.data.supplierid;

          await apiClient.post('/api/supplierevaluations/insert', {
            supplierid: supplierid,
            deliveryTimeliness: deliveryTimeliness,
            qualityScore: qualityScore
          });

          this.showAddDialog = false;
          this.newSupplier = {
            name: '',
            contactPeople: '',
            contactPhone: '',
            deliveryTimeliness: null,
            qualityScore: null
          };
          this.loadSuppliers();
        } catch (err) {
          alert('新增供应商或评分失败: ' + err.message);
          console.error('新增供应商或评分失败:', err);
        }
      },

      cancelAdd() {
        this.newSupplier = {
          name: '',
          contactPeople: '',
          contactPhone: '',
          deliveryTimeliness: null,
          qualityScore: null
        };
        this.showAddDialog = false;
      },

      async deleteSupplier(id) {
        if (!confirm('确定删除？')) return;
        await apiClient.delete(`/api/suppliers/delete/${id}`);
        this.loadSuppliers();
      },

      logout() {
        window.location.href = '/operator.html';
      }
    }
  });

  // 错误处理
  app.config.errorHandler = (err, vm, info) => {
    console.error('Vue 错误:', err, '信息:', info);
    alert('Vue 页面加载出错，请查看控制台日志');
  };

  // 挂载前检查 DOM
  window.addEventListener('DOMContentLoaded', () => {
    try {
      app.use(ElementPlus);
      app.mount('#app');
    } catch (err) {
      console.error('Vue 挂载失败:', err);
      document.getElementById('app').innerHTML = `
        <div style="color: red; font-size: 20px; text-align: center;">
          页面加载失败，请检查控制台日志
        </div>
      `;
    }
  });
</script>
</body>
</html>
